package com.common.auth.controller;

import com.common.api.annontation.Authority;
import com.common.api.annontation.ServiceLog;
import com.common.api.enums.OperateEnum;
import com.common.api.model.PageModel;
import com.common.auth.api.dto.RoleDto;
import com.common.auth.api.service.RoleService;
import com.common.tools.util.BaseBusyServiceUtil;
import com.common.web.annotation.ControllerRequest;
import com.common.web.controller.BaseController;
import com.common.web.dto.request.FuzzyPageDTO;
import com.common.web.dto.response.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * <p>
 * 角色前端控制器
 * </p>
 *
 * @author liuchao
 */
@ServiceLog
@ControllerRequest("/role/")
@Api(tags = "系统授权-角色服务接口")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    /**
     * 查询所有角色信息
     *
     * @param fuzzyPageDTO
     * @return
     */
    @ApiOperation(value = "查询所有角色信息")
    @RequestMapping(value = "queryList")
    public RestResponse queryAllRoles(@RequestBody FuzzyPageDTO fuzzyPageDTO) {
        try {
            PageModel<RoleDto> page = roleService.queryList(fuzzyPageDTO);
            return RestResponse.success("查询角色集合成功!").setData(page);
        } catch (Exception e) {
            return RestResponse.failure("查询角色集合失败：" + e.getMessage());
        }
    }

	/**
	 * @param id
	 * @return
	 */
	@RequestMapping(value="getRoleAuth")
	@ApiOperation(value ="根据主键查询角色")
    public RestResponse getRoleAuth(@RequestBody String roleCode) {
		RoleDto dto= roleService.getRoleAuth(roleCode);	
		return RestResponse.success("根据主键查询角色成功!").setData(dto);
    }

    /**
     * 根据角色编码查询角色已分配的权限资源
     *
     * @param roleCode
     * @return
     */
    @RequestMapping(value = "queryAssignedResourcesByRoleCode")
    @ApiOperation(value = "根据角色编码查询角色已分配的权限资源")
    public RestResponse queryAssignedResourcesByRoleCode(@RequestBody String roleCode) {
        try {
            List<String> assignedResourcesByRoleCode = roleService.getAssignedResourcesByRoleCode(roleCode);
            return RestResponse.success("根据角色编码查询角色已分配的权限资源成功！").setData(assignedResourcesByRoleCode);
        } catch (Exception e) {
            return RestResponse.failure("查询角色已分配的权限资源失败：" + e.getMessage());
        }
    }


    /**
     * 保存角色信息
     *
     * @param dto
     * @return
     */

    @RequestMapping(value = "save")
    @ApiOperation(value = "保存角色信息")
    @Authority(authous = {"role/roleEdit"})
    public RestResponse saveRoleInfo(@RequestBody RoleDto dto) {
        // 抽象操作类型
        String operation = StringUtils.isBlank(dto.getId()) ? OperateEnum.addRole.getEnumName() : OperateEnum.updateRole.getEnumName();
        // 执行相应的操作并记录日志
        try {
            executeRoleOperation(dto, operation);
            return RestResponse.success(operation +"成功！");
        } catch (Exception e) {
            return RestResponse.failure(operation + "失败：" + e.getMessage());
        }
    }

    private void executeRoleOperation(RoleDto dto, String operation) {
        if (OperateEnum.addRole.getEnumName().equals(operation)) {
            roleService.add(dto);
            logOperateDetails(OperateEnum.addRole, getUserCode(), dto);
        } else if (OperateEnum.updateRole.getEnumName().equals(operation)) {
            roleService.modify(dto);
            logOperateDetails(OperateEnum.updateRole, getUserCode(), dto);
        }
    }

    private void logOperateDetails(OperateEnum operateEnum, String userCode, RoleDto dto) {
        BaseBusyServiceUtil.addOperateLog(operateEnum, userCode, dto);
    }


    /**
     * @param idList
     * @return
     */
    @RequestMapping(value = "dels")
    @ApiOperation(value = "根据主键批量删除角色")
    @Authority(authous = {"role/roleEdit"})
    public RestResponse deleteRoleByBatchIds(@RequestBody List<String> idList) {
        try {
            roleService.dels(idList);
            String logMessage = "删除角色" + idList.toString() + "成功！";
            BaseBusyServiceUtil.addOperateLog(OperateEnum.removeRole, getUserCode(), logMessage);
            return RestResponse.success("删除角色成功！");
        } catch (Exception e) {
            return RestResponse.failure("删除角色失败：" + e.getMessage());
        }
    }

	/**
	 * @param RoleDto
	 * @return
	 */
	@RequestMapping(value="saveRoleAuth")
	@ApiOperation(value ="保存角色授权")
    public RestResponse saveRoleAuth(@RequestBody RoleDto dto) {
		roleService.saveRoleAuth(dto);	
        return RestResponse.success("保存角色成功!");
    }
    

    /**
     * @param roleCode
     * @return
     */
    @RequestMapping(value = "enableFlagToUser")
    @ApiOperation(value = "角色启用/禁用")
    @Authority(authous = {"role/roleEdit"})
    public RestResponse enableFlagToRole(@RequestBody String roleCode) {
        try {
            roleService.toggleRoleEnableStatus(roleCode);
            //记录操作日志
            String logMessage = getUserCode() + "启用或禁用角色编码：" + roleCode + "，操作成功";
            BaseBusyServiceUtil.addOperateLog(OperateEnum.updateRole, getUserCode(), logMessage);
            return RestResponse.success("角色启用或禁用成功！");
        } catch (Exception e) {
            return RestResponse.failure("启用或禁用角色失败：" + e.getMessage());
        }
    }

}
